package com.etone.smartAudit.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.etone.smartAudit.domain.CertificateFile;
import com.etone.smartAudit.domain.CertificatePerson;
import com.etone.smartAudit.domain.CertificatePersonInfo;
import com.etone.smartAudit.domain.CertificateUploadFile;
import com.etone.smartAudit.dto.certificate.AddCertificateDTO;
import com.etone.smartAudit.dto.certificate.CertificatePersonDTO;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.CertificatePersonMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etone.smartAudit.vo.certificate.CertificateReplyVO;
import com.etone.smartAudit.vo.certificate.CertificateVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 存证单执行人信息  服务实现类
 * </p>
 *
 * @author jiayen
 * @since 2021-06-08
 */
@Service
public class CertificatePersonService extends ServiceImpl<CertificatePersonMapper, CertificatePerson> {


    @Autowired
    private CertificateUploadFileService certificateUploadFileService;

    @Autowired
    private CertificateReplyService replyService;

    @Autowired
    private CertificateFileService certificateFileService;

    @Value("${handUrl:''}")
    private String handUrl;

    public List<CertificatePerson> getListByFileIdAndType(Integer fileId, Integer... state) {
        //判断上一步的执行人是否执行完毕
        LambdaQueryWrapper<CertificatePerson> query = new LambdaQueryWrapper<>();
        query.eq(CertificatePerson::getCerFileid, fileId);
        query.in(CertificatePerson::getState, state);
        List<CertificatePerson> list = this.list(query);

        return list;
    }

    /***
     * 根据指定文件id获取最后一位执行人列表
     * @param ids
     * @return
     */
    public List<CertificatePerson> getLastListByFileIds(List<Integer> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        List<CertificatePerson> person = baseMapper.getLastListByFileIds(ids);
        return person;
    }

    /***
     * 根据fileId获取执行人员
     * @param fileId
     * @return
     */
    public List<CertificatePerson> getListByFileId(Integer fileId) {
//        LambdaQueryWrapper<CertificatePerson> query = new LambdaQueryWrapper<>();
//        query.eq(CertificatePerson::getCerFileid, fileId);
//        List<CertificatePerson> list = this.list(query);
        List<CertificatePerson> list = baseMapper.getListByFileId(fileId);
        //排序
        List<CertificatePerson> sortList = new ArrayList<>();
        Iterator<CertificatePerson> iterator = list.iterator();
        while (iterator.hasNext()) {
            CertificatePerson vo = iterator.next();
            Integer type = vo.getType() == null ? 0 : vo.getType();
            if (type == 3 || type == 4) {
                sortList.add(vo);
                iterator.remove();
            }
        }
        list.addAll(sortList);
        //获取回复评论
        List<CertificateReplyVO> replys = replyService.getReplyListByCertiFileId(fileId);
        Map<Integer, List<CertificateReplyVO>> replysMap = new HashMap<>();
        replys.stream().forEach(vo -> {
            if (StrUtil.isEmpty(vo.getPersonName())) {
                vo.setPersonName(vo.getAdminName());
            }
            Integer handId = vo.getHandId();
            if (handId != null) {
                List<CertificateReplyVO> temp = replysMap.get(handId);
                if (temp == null) {
                    temp = new ArrayList<>();
                    replysMap.put(handId, temp);
                }
                temp.add(vo);
            }

        });
        List<Integer> personIds = list.stream().map(CertificatePerson::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(personIds)) {
            list.stream().forEach(person -> {
                //获取附件
                person.setFiles(certificateFileService.getFiles(person.getFileIds()));
                person.setReplyList(replysMap.get(person.getId()));
            });
        }
        return list;
    }

    /***
     * 通过返回的url获取数据登录
     * @return
     */
    public CertificatePerson getPersonByUrl(CertificatePersonDTO dto) {
        if (dto == null) {
            throw new CustomParameterizedException("输入正确的执行人信息");
        }
        LambdaQueryWrapper<CertificatePerson> query = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(dto.getLoginKey())) {
            query.eq(CertificatePerson::getUrl, dto.getLoginKey());
        }
        query.eq(CertificatePerson::getCode, dto.getCode());
        List<CertificatePerson> list = this.list(query);
        if (CollectionUtil.isEmpty(list)) {
            throw new CustomParameterizedException("执行人不存在");
        }
        CertificatePerson person = list.get(0);
        //判断该执行人是否还能执行，只有最新的一条能执行
//        //获取最后一个版本存证单
//        hasHandPermission(person);
        return person;
    }

    /**
     * 判断执行人是否是在执行范围
     *
     * @param person
     */
    public void hasHandPermission(CertificatePerson person) {
        //获取最后一个版本存证单
        CertificateFile certificateFile = certificateFileService.lastVersionFile(person.getCerFileid());
        if (!person.getId().equals(certificateFile.getHandPersonId())) {
            throw new CustomParameterizedException("当前临时用户已操作过期");
        }
    }

    /***
     * 设置完整路径
     * @param persons
     */
    public void setHostUrl(List<CertificatePerson> persons) {
        persons.stream().forEach(person -> {
            setHostUrl(person);
        });
    }

    /***
     * 设置完整路径
     * @param person
     */
    public void setHostUrl(CertificatePerson person) {
        person.setUrl(handUrl + person.getUrl());
    }

    /***
     * 获取上一步的扭转人员
     * @param person
     * @return
     */
    public CertificatePerson getLastForwardPersonByPerson(CertificatePerson person) {
        LambdaQueryWrapper<CertificatePerson> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CertificatePerson::getCerFileid, person.getCerFileid())
                .eq(CertificatePerson::getForwordPersonId, person.getId())
                .eq(CertificatePerson::getState, CertificatePerson.YET_READ)
                .orderByDesc(CertificatePerson::getCreateTime);
        List<CertificatePerson> list = this.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /***
     * 获取需求单或者确认单第一位执行人
     * @param cerFileId
     * @return
     */
    public CertificatePerson getFirstHandPerson(Integer cerFileId) {
        LambdaQueryWrapper<CertificatePerson> query = new LambdaQueryWrapper<>();
        query.eq(CertificatePerson::getCerFileid, cerFileId)
                .eq(CertificatePerson::getVersion, 1)
                .orderByAsc(CertificatePerson::getCreateTime);

        List<CertificatePerson> list = this.list(query);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /***
     * 添加指定人关联到指定需求单
     * @param personInfo
     * @param certificateFile
     * @return
     */
    public CertificatePerson addInfoToCer(CertificatePersonInfo personInfo, CertificateVo certificateFile) {
//        certificateFileService.getHandPerson()
        LambdaQueryWrapper<CertificatePerson> query = new LambdaQueryWrapper<>();
        query.eq(CertificatePerson::getCerFileid, certificateFile.getId())
                .eq(CertificatePerson::getPersonInfoId, personInfo.getId());
        List<CertificatePerson> list = this.list(query);
        if(CollectionUtil.isNotEmpty(list)){
            return list.get(0);
        }
        //执行添加
        AddCertificateDTO dto = new AddCertificateDTO();
//        dto.setId(certificateFile.getId());
        dto.setType(certificateFile.getType());
        dto.setHandPersonInfoId(personInfo.getId());
        dto.setHandVersion(certificateFile.getVersion().intValue());
        CertificatePerson handperson = certificateFileService.getHandPerson(dto);
        handperson.setCerFileid(certificateFile.getId());
        handperson.setType(-1);
        this.save(handperson);
        return handperson;
    }
}
